"""
照明状态检测服务
实现灯光开关状态的图像识别，创建自然光照度的分析和评估，开发照明异常的检测和告警
"""
import asyncio
import logging
import cv2
import numpy as np
from datetime import datetime, timedelta
from typing import List, Dict, Optional, Tuple, Any
from uuid import uuid4
import time
from collections import defaultdict, deque
import json
from enum import Enum

logger = logging.getLogger(__name__)


class LightingStatus(str, Enum):
    """照明状态枚举"""
    ON = "on"
    OFF = "off"
    DIMMED = "dimmed"
    UNKNOWN = "unknown"


class LightingType(str, Enum):
    """照明类型枚举"""
    FLUORESCENT = "fluorescent"  # 荧光灯
    LED = "led"  # LED灯
    INCANDESCENT = "incandescent"  # 白炽灯
    NATURAL = "natural"  # 自然光
    MIXED = "mixed"  # 混合光源


class LightingAnomalyType(str, Enum):
    """照明异常类型枚举"""
    FLICKERING = "flickering"  # 闪烁
    OVERBRIGHTNESS = "overbrightness"  # 过亮
    UNDERBRIGHTNESS = "underbrightness"  # 过暗
    COLOR_SHIFT = "color_shift"  # 色温偏移
    UNEVEN_DISTRIBUTION = "uneven_distribution"  # 分布不均
    FAILURE = "failure"  # 故障


class LightingDetectionResult:
    """照明检测结果"""
    def __init__(self, detection_id: str, camera_id: str, zone_id: str,
                 timestamp: datetime, lighting_status: LightingStatus,
                 brightness_level: float, natural_light_level: float,
                 artificial_light_level: float, lighting_type: LightingType,
                 color_temperature: float, uniformity_score: float,
                 detected_anomalies: List[Dict[str, Any]], 
                 energy_efficiency_score: float, recommendations: List[str]):
        self.detection_id = detection_id
        self.camera_id = camera_id
        self.zone_id = zone_id
        self.timestamp = timestamp
        self.lighting_status = lighting_status
        self.brightness_level = brightness_level
        self.natural_light_level = natural_light_level
        self.artificial_light_level = artificial_light_level
        self.lighting_type = lighting_type
        self.color_temperature = color_temperature
        self.uniformity_score = uniformity_score
        self.detected_anomalies = detected_anomalies
        self.energy_efficiency_score = energy_efficiency_score
        self.recommendations = recommendations


class LightingAnomaly:
    """照明异常"""
    def __init__(self, anomaly_id: str, zone_id: str, camera_id: str,
                 anomaly_type: LightingAnomalyType, severity: str,
                 description: str, detected_at: datetime,
                 confidence: float, location: Optional[Tuple[int, int]] = None):
        self.anomaly_id = anomaly_id
        self.zone_id = zone_id
        self.camera_id = camera_id
        self.anomaly_type = anomaly_type
        self.severity = severity
        self.description = description
        self.detected_at = detected_at
        self.confidence = confidence
        self.location = location


class LightingZoneConfig:
    """照明区域配置"""
    def __init__(self, zone_id: str, zone_name: str, zone_type: str,
                 optimal_brightness_range: Tuple[float, float],
                 optimal_color_temp_range: Tuple[float, float],
                 natural_light_weight: float, energy_saving_mode: bool,
                 operating_hours: Dict[str, Tuple[str, str]]):
        self.zone_id = zone_id
        self.zone_name = zone_name
        self.zone_type = zone_type
        self.optimal_brightness_range = optimal_brightness_range
        self.optimal_color_temp_range = optimal_color_temp_range
        self.natural_light_weight = natural_light_weight
        self.energy_saving_mode = energy_saving_mode
        self.operating_hours = operating_hours


class LightingAnalyzer:
    """照明分析器"""
    
    def __init__(self):
        self.brightness_thresholds = {
            'very_dark': 0.1,
            'dark': 0.3,
            'normal': 0.7,
            'bright': 0.9
        }
        
        self.color_temp_ranges = {
            'warm': (2700, 3500),
            'neutral': (3500, 5000),
            'cool': (5000, 6500),
            'daylight': (6500, 8000)
        }
    
    def analyze_brightness(self, image: np.ndarray) -> Dict[str, float]:
        """分析图像亮度"""
        # 转换为灰度图
        if len(image.shape) == 3:
            gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        else:
            gray = image
        
        # 计算整体亮度
        overall_brightness = np.mean(gray) / 255.0
        
        # 计算亮度分布
        hist = cv2.calcHist([gray], [0], None, [256], [0, 256])
        hist_norm = hist.flatten() / hist.sum()
        
        # 计算亮度统计
        brightness_stats = {
            'overall_brightness': overall_brightness,
            'min_brightness': np.min(gray) / 255.0,
            'max_brightness': np.max(gray) / 255.0,
            'std_brightness': np.std(gray) / 255.0,
            'dark_pixels_ratio': np.sum(gray < 64) / gray.size,
            'bright_pixels_ratio': np.sum(gray > 192) / gray.size
        }
        
        return brightness_stats
    
    def detect_lighting_status(self, brightness_stats: Dict[str, float]) -> LightingStatus:
        """检测照明状态"""
        overall_brightness = brightness_stats['overall_brightness']
        bright_ratio = brightness_stats['bright_pixels_ratio']
        
        if overall_brightness < self.brightness_thresholds['very_dark']:
            return LightingStatus.OFF
        elif overall_brightness < self.brightness_thresholds['dark']:
            if bright_ratio > 0.1:  # 有部分亮区域，可能是调光
                return LightingStatus.DIMMED
            else:
                return LightingStatus.OFF
        elif overall_brightness > self.brightness_thresholds['bright']:
            return LightingStatus.ON
        else:
            return LightingStatus.ON
    
    def estimate_natural_light(self, image: np.ndarray, time_of_day: datetime) -> float:
        """估算自然光水平"""
        # 基于时间的自然光估算
        hour = time_of_day.hour
        
        # 简化的自然光模型
        if 6 <= hour <= 18:  # 白天
            # 正弦函数模拟日光变化
            daylight_factor = np.sin((hour - 6) * np.pi / 12)
            base_natural_light = 0.3 + 0.6 * daylight_factor
        else:  # 夜晚
            base_natural_light = 0.05
        
        # 基于图像的自然光检测（简化）
        # 检测窗户区域的亮度
        height, width = image.shape[:2]
        
        # 假设窗户通常在图像上方或侧面
        window_regions = [
            image[:height//3, :],  # 上方区域
            image[:, :width//4],   # 左侧区域
            image[:, -width//4:]   # 右侧区域
        ]
        
        max_window_brightness = 0
        for region in window_regions:
            if len(region.shape) == 3:
                region_gray = cv2.cvtColor(region, cv2.COLOR_BGR2GRAY)
            else:
                region_gray = region
            
            region_brightness = np.mean(region_gray) / 255.0
            max_window_brightness = max(max_window_brightness, region_brightness)
        
        # 结合时间和图像信息
        natural_light_level = (base_natural_light + max_window_brightness * 0.3) / 1.3
        
        return min(1.0, natural_light_level)
    
    def estimate_color_temperature(self, image: np.ndarray) -> float:
        """估算色温"""
        if len(image.shape) != 3:
            return 5000.0  # 默认中性色温
        
        # 计算RGB通道的平均值
        b_mean = np.mean(image[:, :, 0])
        g_mean = np.mean(image[:, :, 1])
        r_mean = np.mean(image[:, :, 2])
        
        # 避免除零
        if b_mean == 0 or r_mean == 0:
            return 5000.0
        
        # 基于蓝红比例估算色温
        br_ratio = b_mean / r_mean
        
        # 简化的色温估算公式
        if br_ratio > 1.2:
            # 偏蓝，高色温
            color_temp = 5000 + (br_ratio - 1.0) * 2000
        elif br_ratio < 0.8:
            # 偏红，低色温
            color_temp = 5000 - (1.0 - br_ratio) * 2000
        else:
            # 中性
            color_temp = 5000
        
        return max(2000, min(8000, color_temp))
    
    def calculate_uniformity(self, image: np.ndarray) -> float:
        """计算照明均匀性"""
        if len(image.shape) == 3:
            gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        else:
            gray = image
        
        # 将图像分成网格
        h, w = gray.shape
        grid_h, grid_w = h // 4, w // 4
        
        grid_brightnesses = []
        for i in range(4):
            for j in range(4):
                y1, y2 = i * grid_h, (i + 1) * grid_h
                x1, x2 = j * grid_w, (j + 1) * grid_w
                
                grid_region = gray[y1:y2, x1:x2]
                grid_brightness = np.mean(grid_region)
                grid_brightnesses.append(grid_brightness)
        
        # 计算均匀性（标准差的倒数）
        brightness_std = np.std(grid_brightnesses)
        brightness_mean = np.mean(grid_brightnesses)
        
        if brightness_mean == 0:
            return 0.0
        
        # 变异系数的倒数作为均匀性指标
        coefficient_of_variation = brightness_std / brightness_mean
        uniformity = 1.0 / (1.0 + coefficient_of_variation)
        
        return uniformity
    
    def detect_anomalies(self, detection_result: LightingDetectionResult,
                        zone_config: LightingZoneConfig) -> List[LightingAnomaly]:
        """检测照明异常"""
        anomalies = []
        
        # 检查亮度异常
        optimal_min, optimal_max = zone_config.optimal_brightness_range
        
        if detection_result.brightness_level < optimal_min * 0.7:
            anomaly = LightingAnomaly(
                anomaly_id=str(uuid4()),
                zone_id=detection_result.zone_id,
                camera_id=detection_result.camera_id,
                anomaly_type=LightingAnomalyType.UNDERBRIGHTNESS,
                severity="medium",
                description=f"亮度过低: {detection_result.brightness_level:.2f}, 建议范围: {optimal_min:.2f}-{optimal_max:.2f}",
                detected_at=detection_result.timestamp,
                confidence=0.8
            )
            anomalies.append(anomaly)
        
        elif detection_result.brightness_level > optimal_max * 1.3:
            anomaly = LightingAnomaly(
                anomaly_id=str(uuid4()),
                zone_id=detection_result.zone_id,
                camera_id=detection_result.camera_id,
                anomaly_type=LightingAnomalyType.OVERBRIGHTNESS,
                severity="medium",
                description=f"亮度过高: {detection_result.brightness_level:.2f}, 建议范围: {optimal_min:.2f}-{optimal_max:.2f}",
                detected_at=detection_result.timestamp,
                confidence=0.8
            )
            anomalies.append(anomaly)
        
        # 检查色温异常
        temp_min, temp_max = zone_config.optimal_color_temp_range
        
        if not (temp_min <= detection_result.color_temperature <= temp_max):
            anomaly = LightingAnomaly(
                anomaly_id=str(uuid4()),
                zone_id=detection_result.zone_id,
                camera_id=detection_result.camera_id,
                anomaly_type=LightingAnomalyType.COLOR_SHIFT,
                severity="low",
                description=f"色温偏离: {detection_result.color_temperature:.0f}K, 建议范围: {temp_min:.0f}K-{temp_max:.0f}K",
                detected_at=detection_result.timestamp,
                confidence=0.6
            )
            anomalies.append(anomaly)
        
        # 检查均匀性异常
        if detection_result.uniformity_score < 0.6:
            anomaly = LightingAnomaly(
                anomaly_id=str(uuid4()),
                zone_id=detection_result.zone_id,
                camera_id=detection_result.camera_id,
                anomaly_type=LightingAnomalyType.UNEVEN_DISTRIBUTION,
                severity="medium",
                description=f"照明分布不均: 均匀性评分 {detection_result.uniformity_score:.2f}",
                detected_at=detection_result.timestamp,
                confidence=0.7
            )
            anomalies.append(anomaly)
        
        return anomalies


class EnergyEfficiencyCalculator:
    """能效计算器"""
    
    def calculate_efficiency_score(self, detection_result: LightingDetectionResult,
                                 zone_config: LightingZoneConfig) -> float:
        """计算能效评分"""
        score = 100.0
        
        # 亮度效率（避免过度照明）
        optimal_min, optimal_max = zone_config.optimal_brightness_range
        optimal_mid = (optimal_min + optimal_max) / 2
        
        brightness_deviation = abs(detection_result.brightness_level - optimal_mid)
        brightness_penalty = brightness_deviation * 30
        score -= brightness_penalty
        
        # 自然光利用效率
        natural_light_bonus = detection_result.natural_light_level * zone_config.natural_light_weight * 20
        score += natural_light_bonus
        
        # 均匀性奖励
        uniformity_bonus = detection_result.uniformity_score * 10
        score += uniformity_bonus
        
        # 异常惩罚
        anomaly_penalty = len(detection_result.detected_anomalies) * 5
        score -= anomaly_penalty
        
        return max(0, min(100, score))
    
    def generate_energy_recommendations(self, detection_result: LightingDetectionResult,
                                      zone_config: LightingZoneConfig) -> List[str]:
        """生成节能建议"""
        recommendations = []
        
        # 基于自然光的建议
        if detection_result.natural_light_level > 0.6 and detection_result.artificial_light_level > 0.5:
            recommendations.append("自然光充足，建议调低人工照明或使用调光系统")
        
        # 基于亮度的建议
        optimal_min, optimal_max = zone_config.optimal_brightness_range
        
        if detection_result.brightness_level > optimal_max:
            recommendations.append("照明亮度超出需求，建议降低亮度以节约能源")
        
        # 基于时间的建议
        current_hour = detection_result.timestamp.hour
        weekday = detection_result.timestamp.strftime('%A').lower()
        
        if weekday in zone_config.operating_hours:
            start_time, end_time = zone_config.operating_hours[weekday]
            start_hour = int(start_time.split(':')[0])
            end_hour = int(end_time.split(':')[0])
            
            if not (start_hour <= current_hour <= end_hour):
                if detection_result.lighting_status == LightingStatus.ON:
                    recommendations.append("非工作时间检测到照明开启，建议关闭以节约能源")
        
        # 基于均匀性的建议
        if detection_result.uniformity_score < 0.7:
            recommendations.append("照明分布不均，建议调整灯具位置或增加局部照明")
        
        # 基于色温的建议
        if detection_result.color_temperature > 6000 and current_hour > 18:
            recommendations.append("晚间建议使用暖色温照明，有助于节能和健康")
        
        return recommendations


class LightingDetectionService:
    """照明状态检测服务"""
    
    def __init__(self):
        self.analyzer = LightingAnalyzer()
        self.efficiency_calculator = EnergyEfficiencyCalculator()
        
        self.detection_results: List[LightingDetectionResult] = []
        self.anomalies: List[LightingAnomaly] = []
        self.zone_configs: Dict[str, LightingZoneConfig] = {}
        
        # 服务状态
        self._running = False
        self._monitoring_task = None
        self.monitoring_interval = 300.0  # 5分钟检查一次
        
        # 初始化默认配置
        self._initialize_default_configs()
        
        # 统计信息
        self.stats = {
            'total_detections': 0,
            'anomalies_detected': 0,
            'average_brightness': 0.0,
            'average_efficiency_score': 0.0,
            'energy_savings_potential': 0.0
        }
    
    def _initialize_default_configs(self):
        """初始化默认区域配置"""
        # 教室配置
        classroom_config = LightingZoneConfig(
            zone_id="default_classroom",
            zone_name="默认教室",
            zone_type="classroom",
            optimal_brightness_range=(0.4, 0.7),
            optimal_color_temp_range=(4000, 6000),
            natural_light_weight=0.3,
            energy_saving_mode=True,
            operating_hours={
                'monday': ('08:00', '18:00'),
                'tuesday': ('08:00', '18:00'),
                'wednesday': ('08:00', '18:00'),
                'thursday': ('08:00', '18:00'),
                'friday': ('08:00', '18:00'),
                'saturday': ('09:00', '17:00'),
                'sunday': ('09:00', '17:00')
            }
        )
        
        # 办公室配置
        office_config = LightingZoneConfig(
            zone_id="default_office",
            zone_name="默认办公室",
            zone_type="office",
            optimal_brightness_range=(0.5, 0.8),
            optimal_color_temp_range=(4500, 6500),
            natural_light_weight=0.4,
            energy_saving_mode=True,
            operating_hours={
                'monday': ('09:00', '18:00'),
                'tuesday': ('09:00', '18:00'),
                'wednesday': ('09:00', '18:00'),
                'thursday': ('09:00', '18:00'),
                'friday': ('09:00', '18:00'),
                'saturday': ('10:00', '16:00'),
                'sunday': ('10:00', '16:00')
            }
        )
        
        # 走廊配置
        hallway_config = LightingZoneConfig(
            zone_id="default_hallway",
            zone_name="默认走廊",
            zone_type="hallway",
            optimal_brightness_range=(0.3, 0.6),
            optimal_color_temp_range=(3500, 5500),
            natural_light_weight=0.2,
            energy_saving_mode=True,
            operating_hours={
                'monday': ('07:00', '20:00'),
                'tuesday': ('07:00', '20:00'),
                'wednesday': ('07:00', '20:00'),
                'thursday': ('07:00', '20:00'),
                'friday': ('07:00', '20:00'),
                'saturday': ('08:00', '19:00'),
                'sunday': ('08:00', '19:00')
            }
        )
        
        self.zone_configs = {
            "classroom": classroom_config,
            "office": office_config,
            "hallway": hallway_config
        }
    
    async def start_service(self):
        """启动服务"""
        if self._running:
            return
        
        self._running = True
        self._monitoring_task = asyncio.create_task(self._monitoring_loop())
        logger.info("Lighting detection service started")
    
    async def stop_service(self):
        """停止服务"""
        self._running = False
        if self._monitoring_task:
            self._monitoring_task.cancel()
            try:
                await self._monitoring_task
            except asyncio.CancelledError:
                pass
        logger.info("Lighting detection service stopped")
    
    async def _monitoring_loop(self):
        """监控循环"""
        while self._running:
            try:
                await self._periodic_monitoring()
                await asyncio.sleep(self.monitoring_interval)
            except asyncio.CancelledError:
                break
            except Exception as e:
                logger.error(f"Error in lighting detection monitoring loop: {e}")
                await asyncio.sleep(60.0)
    
    async def _periodic_monitoring(self):
        """周期性监控"""
        # 清理过期数据
        cutoff_time = datetime.now() - timedelta(days=7)
        
        self.detection_results = [
            result for result in self.detection_results
            if result.timestamp > cutoff_time
        ]
        
        self.anomalies = [
            anomaly for anomaly in self.anomalies
            if anomaly.detected_at > cutoff_time
        ]
        
        # 更新统计信息
        self._update_statistics()
    
    def _update_statistics(self):
        """更新统计信息"""
        if not self.detection_results:
            return
        
        self.stats['total_detections'] = len(self.detection_results)
        self.stats['anomalies_detected'] = len(self.anomalies)
        
        # 计算平均亮度
        brightness_values = [r.brightness_level for r in self.detection_results]
        self.stats['average_brightness'] = np.mean(brightness_values)
        
        # 计算平均能效评分
        efficiency_scores = [r.energy_efficiency_score for r in self.detection_results]
        self.stats['average_efficiency_score'] = np.mean(efficiency_scores)
        
        # 估算节能潜力
        inefficient_detections = [r for r in self.detection_results if r.energy_efficiency_score < 70]
        self.stats['energy_savings_potential'] = len(inefficient_detections) / len(self.detection_results) * 100
    
    async def detect_lighting_status(self, image: np.ndarray, camera_id: str,
                                   zone_id: str) -> LightingDetectionResult:
        """检测照明状态"""
        try:
            detection_id = str(uuid4())
            timestamp = datetime.now()
            
            # 分析图像亮度
            brightness_stats = self.analyzer.analyze_brightness(image)
            
            # 检测照明状态
            lighting_status = self.analyzer.detect_lighting_status(brightness_stats)
            
            # 估算自然光和人工光
            natural_light_level = self.analyzer.estimate_natural_light(image, timestamp)
            
            # 计算人工光水平
            artificial_light_level = max(0, brightness_stats['overall_brightness'] - natural_light_level * 0.5)
            
            # 估算色温
            color_temperature = self.analyzer.estimate_color_temperature(image)
            
            # 计算均匀性
            uniformity_score = self.analyzer.calculate_uniformity(image)
            
            # 确定照明类型
            lighting_type = self._determine_lighting_type(color_temperature, brightness_stats)
            
            # 获取区域配置
            zone_config = self._get_zone_config(zone_id)
            
            # 创建初步检测结果
            detection_result = LightingDetectionResult(
                detection_id=detection_id,
                camera_id=camera_id,
                zone_id=zone_id,
                timestamp=timestamp,
                lighting_status=lighting_status,
                brightness_level=brightness_stats['overall_brightness'],
                natural_light_level=natural_light_level,
                artificial_light_level=artificial_light_level,
                lighting_type=lighting_type,
                color_temperature=color_temperature,
                uniformity_score=uniformity_score,
                detected_anomalies=[],
                energy_efficiency_score=0.0,
                recommendations=[]
            )
            
            # 计算能效评分
            detection_result.energy_efficiency_score = self.efficiency_calculator.calculate_efficiency_score(
                detection_result, zone_config
            )
            
            # 检测异常
            anomalies = self.analyzer.detect_anomalies(detection_result, zone_config)
            detection_result.detected_anomalies = [
                {
                    'type': anomaly.anomaly_type.value,
                    'severity': anomaly.severity,
                    'description': anomaly.description,
                    'confidence': anomaly.confidence
                }
                for anomaly in anomalies
            ]
            
            # 生成建议
            detection_result.recommendations = self.efficiency_calculator.generate_energy_recommendations(
                detection_result, zone_config
            )
            
            # 存储结果
            self.detection_results.append(detection_result)
            self.anomalies.extend(anomalies)
            
            # 保持最近1000个检测结果
            if len(self.detection_results) > 1000:
                self.detection_results = self.detection_results[-1000:]
            
            # 保持最近500个异常记录
            if len(self.anomalies) > 500:
                self.anomalies = self.anomalies[-500:]
            
            logger.info(f"Lighting detection completed for zone {zone_id}: {lighting_status.value}, brightness {brightness_stats['overall_brightness']:.2f}")
            
            return detection_result
            
        except Exception as e:
            logger.error(f"Failed to detect lighting status: {e}")
            raise
    
    def _determine_lighting_type(self, color_temperature: float, 
                                brightness_stats: Dict[str, float]) -> LightingType:
        """确定照明类型"""
        # 基于色温判断
        if 2700 <= color_temperature <= 3500:
            return LightingType.INCANDESCENT
        elif 4000 <= color_temperature <= 5000:
            return LightingType.FLUORESCENT
        elif 5000 <= color_temperature <= 6500:
            return LightingType.LED
        elif color_temperature > 6500:
            return LightingType.NATURAL
        else:
            return LightingType.MIXED
    
    def _get_zone_config(self, zone_id: str) -> LightingZoneConfig:
        """获取区域配置"""
        # 尝试精确匹配
        if zone_id in self.zone_configs:
            return self.zone_configs[zone_id]
        
        # 基于区域类型匹配
        if 'classroom' in zone_id.lower():
            return self.zone_configs['classroom']
        elif 'office' in zone_id.lower():
            return self.zone_configs['office']
        elif 'hallway' in zone_id.lower():
            return self.zone_configs['hallway']
        else:
            # 返回默认配置
            return self.zone_configs['classroom']
    
    async def get_detection_results(self, zone_id: Optional[str] = None,
                                  start_time: Optional[datetime] = None,
                                  end_time: Optional[datetime] = None,
                                  limit: int = 100) -> List[LightingDetectionResult]:
        """获取检测结果"""
        results = self.detection_results
        
        # 过滤条件
        if zone_id:
            results = [r for r in results if r.zone_id == zone_id]
        
        if start_time:
            results = [r for r in results if r.timestamp >= start_time]
        
        if end_time:
            results = [r for r in results if r.timestamp <= end_time]
        
        # 按时间倒序排列
        results.sort(key=lambda x: x.timestamp, reverse=True)
        
        return results[:limit]
    
    async def get_anomalies(self, zone_id: Optional[str] = None,
                          anomaly_type: Optional[LightingAnomalyType] = None,
                          severity: Optional[str] = None,
                          limit: int = 100) -> List[LightingAnomaly]:
        """获取异常记录"""
        anomalies = self.anomalies
        
        # 过滤条件
        if zone_id:
            anomalies = [a for a in anomalies if a.zone_id == zone_id]
        
        if anomaly_type:
            anomalies = [a for a in anomalies if a.anomaly_type == anomaly_type]
        
        if severity:
            anomalies = [a for a in anomalies if a.severity == severity]
        
        # 按时间倒序排列
        anomalies.sort(key=lambda x: x.detected_at, reverse=True)
        
        return anomalies[:limit]
    
    async def get_zone_lighting_stats(self, zone_id: str, days: int = 7) -> Dict[str, Any]:
        """获取区域照明统计"""
        end_time = datetime.now()
        start_time = end_time - timedelta(days=days)
        
        # 获取时间范围内的检测结果
        zone_results = [
            r for r in self.detection_results
            if r.zone_id == zone_id and start_time <= r.timestamp <= end_time
        ]
        
        if not zone_results:
            return {
                'zone_id': zone_id,
                'total_detections': 0,
                'average_brightness': 0.0,
                'average_efficiency': 0.0,
                'lighting_status_distribution': {},
                'anomaly_count': 0
            }
        
        # 计算统计指标
        total_detections = len(zone_results)
        average_brightness = np.mean([r.brightness_level for r in zone_results])
        average_efficiency = np.mean([r.energy_efficiency_score for r in zone_results])
        
        # 照明状态分布
        status_distribution = defaultdict(int)
        for result in zone_results:
            status_distribution[result.lighting_status.value] += 1
        
        # 异常统计
        zone_anomalies = [
            a for a in self.anomalies
            if a.zone_id == zone_id and start_time <= a.detected_at <= end_time
        ]
        
        return {
            'zone_id': zone_id,
            'total_detections': total_detections,
            'average_brightness': average_brightness,
            'average_efficiency': average_efficiency,
            'average_natural_light': np.mean([r.natural_light_level for r in zone_results]),
            'average_uniformity': np.mean([r.uniformity_score for r in zone_results]),
            'lighting_status_distribution': dict(status_distribution),
            'anomaly_count': len(zone_anomalies),
            'period_days': days
        }
    
    def add_zone_config(self, config: LightingZoneConfig):
        """添加区域配置"""
        self.zone_configs[config.zone_id] = config
        logger.info(f"Added lighting zone config: {config.zone_id}")
    
    def get_zone_configs(self) -> List[LightingZoneConfig]:
        """获取所有区域配置"""
        return list(self.zone_configs.values())
    
    def get_statistics(self) -> Dict[str, Any]:
        """获取统计信息"""
        return self.stats.copy()


# 全局照明检测服务实例
lighting_detection_service = LightingDetectionService()